package com.leetcode.LeetCode精选TOP面试题;

/**
 * @author 覃国强
 * @date 2022-06-17 17:12
 */
public class 题库_0123_买卖股票的最佳时机III {

  static
  class Solution {
    public int maxProfit(int[] prices) {
      if (prices == null || prices.length == 0) {
        return 0;
      }
      // 买入一次
      int buy1 = -prices[0];
      // 卖出一次
      int sell1 = 0;
      // 买入两次
      int buy2 = -prices[0];
      // 卖出两次
      int sell2 = 0;

      for (int i = 1; i < prices.length; ++i) {
        int todayBuy1 = Math.max(buy1, -prices[i]);
        int todaySell1 = Math.max(sell1, buy1 + prices[i]);
        int todayBuy2 = Math.max(buy2, sell1 - prices[i]);
        int todaySell2 = Math.max(sell2, buy2 + prices[i]);
        buy1 = todayBuy1;
        sell1 = todaySell1;
        buy2 = todayBuy2;
        sell2 = todaySell2;
      }

      return sell2;
    }
  }
}
